
var { WebSocketServer } = require('ws');  // webSocket插件 
const port = 4800;
const hostname = "0.0.0.0"
const wss = new WebSocketServer({ port, hostname });


console.log(`Socket Server is listen at ${port}`)

const querystring = require('querystring')

var count = 0;
var typeInof = "WuHan2114__"
var onLineUser = {}  // 存储所有的客户端对象  

// # 监听客户端链接
wss.on("connection", (socket) => {
    console.log("我上线了")
    console.log(querystring.stringify(socket));

    count++;
    socket.name = typeInof + count;   // WuHan2114__1  每个客户端取一个名字  
    onLineUser[socket.name] = socket;   // key-value 

    // # 监听客户端发来的消息
    socket.on("message", (msg) => {
        console.log(msg)
        // # 转发消息给其他的客户端
        boradCast(socket, msg);
    })

    // # 监听客户端的关闭和异常  
    socket.on("error", (err) => {
        console.log(err)
    })
    // # 客户端断开连看看  
    socket.on("close", () => {
        boradCast(socket, '886,我走了哦');
        // 对象删除  
        delete onLineUser[socket.name]  // delete object[key] 删除对象的某一个属性 
    })
})

function boradCast(socket, msg) {   // A:晚上通讯 
    for (var key in onLineUser) {
        var date = new Date()
        var hour = date.getHours()
        var min = date.getMinutes()
        onLineUser[key].send(`${socket.name} 说 (${hour}:${min}) : ${msg}`)   // send 转发消息 
    }
}